package com.example.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.Result;
import com.example.springboot.controller.request.BikePageRequest;
import com.example.springboot.controller.request.CategoryPageRequest;
import com.example.springboot.entity.Admin;
import com.example.springboot.entity.Bike;
import com.example.springboot.entity.Hire;
import com.example.springboot.service.BikeService;
import com.example.springboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * ClassName:BikeController
 * Package:com.example.springboot.controller
 * Description:
 *
 * @Author: Gao
 * @Create: 2023/2/6 - 19:25
 */
@Slf4j
@RestController
@RequestMapping( "/bike")
public class BikeController {
    //System.getProperty方法获取的属性是由JVM加载时初始化的属性，"user.dir"代表用户当前的工作目录。
    private static final String BASE_FILE_PATH = System.getProperty("user.dir") + "/files/";
    @Autowired
    BikeService bikeService;


    /**
          * 上传文件,不带token
          * @param file
          * @return
          * @throws
          */
    @PostMapping("/file/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)) {
            return Result.error("文件上传失败");
        }
        long flag = System.currentTimeMillis();
        String filePath = BASE_FILE_PATH + flag + "_" + originalFilename;//文件以时间戳加上原始名称命名
        try {
            FileUtil.mkParentDirs(filePath);  // 创建父级目录，即创建files文件（若不存在files）
            file.transferTo(FileUtil.file(filePath));
            String url = "http://localhost:9090/api/bike/file/download/" + flag;
            if (originalFilename.endsWith("png") || originalFilename.endsWith("jpg")) {
                url += "?play=1";
            }
            //返回url
            return Result.success(url);
        } catch (Exception e) {
            log.info("文件上传失败", e);
            return Result.error("文件上传失败");
        }
    }

    /**
     * 下载文件，不带token，此处GetMapping中的url为http://localhost:9090/api/bike/file/download/{flag}，与上传时文件存储的url对应
     * @param flag
     * @param response
     * @throws
     */
    @GetMapping("/file/download/{flag}")
    public void downloadFile(@PathVariable String flag, @RequestParam(required = false) String play, HttpServletResponse response) {
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(BASE_FILE_PATH);
        String fileName = fileNames.stream().filter(s -> s.contains(flag)).findAny().orElse("");// System.currentTimeMillis() + originalFilename
        try {
            if(StrUtil.isNotEmpty(fileName)){
                String realName = fileName.substring(fileName.lastIndexOf("_") + 1);
                if("1".equals(play)){
                    response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(realName, "UTF-8"));
                }else {
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realName, "UTF-8"));
                }
                byte[] bytes = FileUtil.readBytes(BASE_FILE_PATH + fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            log.error("文件下载失败",e);
        }
    }

//    /**
//     * 上传文件,带token
//     * @param file
//     * @return
//     * @throws
//     */
//    @PostMapping("/file/upload")
//    public Result uploadFile(@RequestParam("file") MultipartFile file) {
//        String originalFilename = file.getOriginalFilename();
//        if (StrUtil.isBlank(originalFilename)) {
//            return Result.error("文件上传失败");
//        }
//        long flag = System.currentTimeMillis();
//        String filePath = BASE_FILE_PATH + flag + "_" + originalFilename;
//        try {
//            FileUtil.mkParentDirs(filePath);  // 创建父级目录
//            file.transferTo(FileUtil.file(filePath));
//            Admin currentAdmin = TokenUtils.getCurrentAdmin();
//            String token = TokenUtils.genToken(currentAdmin.getId().toString(), currentAdmin.getPassword(), 365);
//            String url = "http://localhost:9090/api/bike/file/download/" + flag + "?&token=" + token;
//            if (originalFilename.endsWith("png") || originalFilename.endsWith("jpg")) {
//                url += "&play=1";
//            }
//            return Result.success(url);
//        } catch (Exception e) {
//            log.info("文件上传失败", e);
//        }
//        return Result.error("文件上传失败");
//    }
//
//    /**
//     * 下载文件，带token
//     * @param flag
//     * @param response
//     * @throws
//     */
//    @GetMapping("/file/download/{flag}")
//    public void downloadFile(@PathVariable String flag, @RequestParam(required = false) String play, HttpServletResponse response) {
//        OutputStream os;
//        List<String> fileNames = FileUtil.listFileNames(BASE_FILE_PATH);
//        String fileName = fileNames.stream().filter(s -> s.contains(flag)).findAny().orElse("");// System.currentTimeMillis() + originalFilename
//        try {
//            if(StrUtil.isNotEmpty(fileName)){
//                String realName = fileName.substring(fileName.lastIndexOf("_") + 1);
//                if("1".equals(play)){
//                    response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(realName, "UTF-8"));
//                }else {
//                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realName, "UTF-8"));
//                }
//                byte[] bytes = FileUtil.readBytes(BASE_FILE_PATH + fileName);
//                os = response.getOutputStream();
//                os.write(bytes);
//                os.flush();
//                os.close();
//            }
//        } catch (Exception e) {
//            log.error("文件下载失败",e);
//        }
//    }

    @GetMapping("/")
    public Result list(){
        List<Bike> categories = bikeService.list();
        return Result.success(categories);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") int id){
        Bike bike = bikeService.getById(id);
        return Result.success(bike);
    }

    @GetMapping("/page")
    public Result page(BikePageRequest pageRequest){
        Object page = bikeService.page(pageRequest);
        return Result.success(page);
    }

    @PutMapping("/")
    public Result update(@RequestBody Bike bike){
        bikeService.update(bike);
        return Result.success();
    }

    @PostMapping("/")
    public Result save(@RequestBody Bike bike){
        bikeService.save(bike);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id){
        bikeService.deleteById(id);
        return Result.success();
    }
    
}
